package io.virtualapp.abs.ui;

import org.greenrobot.eventbus.EventBus;
import org.jdeferred.android.AndroidDeferredManager;
import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.alipay.sdk.app.PayTask;
import com.flurry.android.FlurryAgent;

import java.util.Map;

import io.virtualapp.VCommends;
import io.virtualapp.abs.BasePresenter;
import io.virtualapp.bean.ApliyBean;
import io.virtualapp.bean.EventBusBean;
import io.virtualapp.bean.EventBusMakeBean;
import io.virtualapp.bean.PayResult;
import io.virtualapp.bean.UpdateBean;
import io.virtualapp.bean.Vip;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.http.HttpUtils;
import io.virtualapp.mylibrary.util.SpUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author Lody
 */
public class VFragment<T extends BasePresenter> extends Fragment {
	public static Vip vip;
	protected T mPresenter;
	protected Fragment mFragment;

	private static final int SDK_PAY_FLAG = 1;
	private static final int SDK_PAY_FLAG2 = 2;
	protected PaysuccessListener PayListener;
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what){
				case SDK_PAY_FLAG:
					PayResult payResult = new PayResult((Map<String, String>) msg.obj);
					switch (payResult.getResultStatus()){
						case "9000":
							updataVip();
							EventBus.getDefault().post(new EventBusMakeBean("successPay"));
							if (PayListener!=null){
								PayListener.PaySuccess();
							}
							break;
						case "8000":
							ToastUtils.showShortToast("正在处理中");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						case "4000":
							ToastUtils.showShortToast("订单支付失败");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						case "5000":
							ToastUtils.showShortToast("重复请求");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						case "6001":
							ToastUtils.showShortToast("已取消支付");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						case "6002":
							ToastUtils.showShortToast("网络连接出错");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						case "6004":
							ToastUtils.showShortToast("正在处理中");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
						default:
							ToastUtils.showShortToast("支付失败");
							if (PayListener!=null){
								PayListener.PayFail(payResult.getResultStatus());
							}
							break;
					}
					//有支付意愿的，取消他的不再提醒
					break;
				case SDK_PAY_FLAG2:
					PayResult payResult_2 = new PayResult((Map<String, String>) msg.obj);
					switch (payResult_2.getResultStatus()){
						case "9000":
							updataVip();
							EventBus.getDefault().post(new EventBusMakeBean("successPay_one"));
							SpUtils.getInstance().putLong(VCommends.APPFIRSTINTIME,4124250886000l);
							if (PayListener!=null){
								PayListener.PaySuccess();
							}
							break;
						default:
							ToastUtils.showShortToast("支付失败");
							break;
					}
					break;

			}

		}
	};
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mFragment=this;

		// 获取vip状态
		if (DataSupport.findFirst(Vip.class) != null) {
			vip = DataSupport.findFirst(Vip.class);
		}

	}
	public T getPresenter() {
		return mPresenter;
	}
	protected void updataVip(){
		HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
			@Override
			public void onRequestBefore() {

			}

			@Override
			public void onFailure(Request request, Exception e) {

			}

			@Override
			public void onSuccess(Response response, UpdateBean o) {
				if (o!=null&&response.isSuccessful()){
					vip = o.getVip();
					if (DataSupport.findFirst(Vip.class) != null){
						DataSupport.deleteAll(Vip.class);
					}
					vip.save();
				}
			}
			@Override
			public void onError(Response response, int errorCode, Exception e) {

			}
		});
	}
	public void setPresenter(T presenter) {
		this.mPresenter = presenter;
	}

	protected AndroidDeferredManager defer() {
		return VUiKit.defer();
	}

	public void finishActivity() {
		Activity activity = getActivity();
		if (activity != null) {
			activity.finish();
		}
	}

	public void destroy() {
		finishActivity();
	}
	public interface PaysuccessListener{
		public void PaySuccess();
		public void PayFail(String resultstatu);
	}
	/**
	 *      支付宝购买
	 * @param pid
	 */
	protected void pay(int pid,boolean isFirstPay){
		HttpUtils.getInstance().postOrder(1,pid,0,2,new BaseCallback<ApliyBean>(){
			@Override
			public void onRequestBefore() {

			}

			@Override
			public void onFailure(Request request, Exception e) {
				ToastUtils.showShortToast("链接超时");
			}

			@Override
			public void onSuccess(Response response, ApliyBean apliyBean) {
				if (response.isSuccessful()){
					if (apliyBean != null){
						if (!apliyBean.isIssucc()){
							ToastUtils.showShortToast(apliyBean.getMsg());
							return;
						}
						Runnable runnable = ()->{
							PayTask alipay = new PayTask(getActivity());
							Map<String, String> map = alipay.payV2(apliyBean.getPackage_str(),true);
							Message msg = new Message();
							if (isFirstPay){
								msg.what = SDK_PAY_FLAG2;
							}else {
								msg.what = SDK_PAY_FLAG;
							}
							msg.obj = map;
							mHandler.sendMessage(msg);


						};

						Thread payThread = new Thread(runnable);
						payThread.start();
					}
				}
			}
			@Override
			public void onError(Response response, int errorCode, Exception e) {

			}
		});
	}

	public Fragment getmFragment() {
		return this;
	}


	public Context getContext() {
		return getActivity();
	}
	@Override
	public void onStart() {
		super.onStart();
		FlurryAgent.onStartSession(getActivity());
	}

	@Override
	public void onStop() {
		super.onStop();
		FlurryAgent.onEndSession(getActivity());
	}

}
